package com.goti.nettyClient.nettyClient;

import com.goti.nettyClient.handler.ClientDispatcherHandler;
import com.goti.nettyClient.protobuf.MsgPro;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: 8.28_sao_year
 * @package: com.tyhc.nettyClient
 * @description: netyyClient
 * @author: goti
 * @create: 2019-11-26 10:54
 */
@Component
public class NettyClient {

    private Bootstrap b;
    private  String host;
    private  int port;
    private Channel channel;

    //连接服务端的端口号地址和端口号

    public void init(String host,int port) {
        this.host = host;
        this.port = port;
        final EventLoopGroup group = new NioEventLoopGroup();

        b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)  // 使用NioSocketChannel来作为连接用的channel类
                .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                    @Override
                    public void initChannel(SocketChannel socketChannel) throws Exception {
                        System.out.println("正在连接中...");
                        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                        socketChannel.pipeline().addLast(new ProtobufDecoder(MsgPro.UserMsg.getDefaultInstance()));
                        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                        socketChannel.pipeline().addLast(new ProtobufEncoder());
                        socketChannel.pipeline().addLast(new ClientDispatcherHandler());
                    }
                });
        doConnect();
    }

    public Channel getChannel() {
        return channel;
    }

    public void doConnect(){
        System.out.println("----");
        if (channel != null && channel.isActive()) {

            return;
        }
        System.out.println("开启重新连接");
        //发起异步连接请求，绑定连接端口和host信息
        final ChannelFuture future;
        try {
            future = b.connect(host, port);
            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture arg0) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("连接服务器成功");

                    } else {
                        System.out.println("连接服务器失败");
                        future.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    init(host,port);
                                }catch (Exception e){
                                    System.out.println("连接服务器失败");
                                }

                            }
                        }, 2, TimeUnit.SECONDS);

                    }
                }
            });
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
